<template>
  <BottomDialog :is-show="dialog">
    <template #append-icon>
      <button @click="close()">
        <Icon size="24" name="close"></Icon>
      </button>
    </template>
    <template #title>
      <div>
        {{ $t(title) }}
      </div>
    </template>
    <template #body>
      <v-row style="margin-bottom: 5rem">
        <v-col v-for="(card, index) in totalPerformanceCards" :key="`performance-card-${index}`" cols="6">
          <EarnPerformCard :label="card.label" :text="card.text"></EarnPerformCard>
        </v-col>
      </v-row>
    </template>
  </BottomDialog>
</template>
<script setup>
import BottomDialog from '@/components/dialogs/BottomDialog.vue'
import EarnPerformCard from '@/components/mine/EarnPerformCard.vue'
import API from '@/http'
import { useEarnStore } from '@/store/earn.js'
import { storeToRefs } from 'pinia'
import { computed, ref, watch } from 'vue'
import { find } from 'lodash-es'
import { toDateYmd } from '@/utils/string-helper'
import { useAccountStore } from '@/store/account'
import { VRow, VCol } from 'vuetify/components'

const accountStore = useAccountStore()
const { isLogin } = storeToRefs(accountStore)

const totalPerformanceCards = ref([
  { label: 'info.earnDialog.totalWatches', text: 'null', key: 'view_num' },
  { label: 'info.earnDialog.dailyAvgWatches', text: 'null', key: 'view_avg_num' },
  { label: 'info.earnDialog.likes', text: 'null', key: 'like_num' },
  { label: 'info.earnDialog.comments', text: 'null', key: 'comment_num' },
  { label: 'info.earnDialog.shares', text: 'null', key: 'share_num' },
  { label: 'info.earnDialog.sales', text: 'null', key: 'buy_num' },
  { label: 'info.earnDialog.profits', text: 'null', key: 'in_come' },
  { label: 'label.earnIndex.completionTimes', text: '0', key: 'play_complete_num' },
  { label: 'label.earnIndex.broadcastRevenueIncentive', text: '$0.00', key: 'in_come_play_complete' },
  
])
const earnStore = useEarnStore()
const { dialog, selectedFilter, startDate, endDate } = storeToRefs(earnStore)
const { close, filters } = earnStore
const title = computed(() => find(filters, { value: selectedFilter.value.value })?.label)

const fetch = async (filter) => {
  if (!isLogin.value) return
  try {
    const response = await API.Earn.count({
      data: {
        type: filter.value,
        start: toDateYmd(startDate.value),
        end: toDateYmd(endDate.value),
      },
    })

    for (const [key, value] of Object.entries(response)) {
      if (typeof value !== 'object') {
        const card = find(totalPerformanceCards.value, { key })
        
        if (!card) return

        if (key === 'in_come'||key === 'in_come_play_complete') {
          card.text = '$' + value.toFixed(2)
          continue
        }
        card.text = value.toString()
      }
    }
  } catch (e) {
    console.error(e)
  }
}
watch(selectedFilter, fetch, { immediate: true })
</script>
